package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Reference
    private SpuService spuService;

    @Reference
    private CategoryService categoryService;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${pagePath}")
    private String pagePath;

    //生成商品详细页
    @GetMapping("/createPage")
    public void createPage(String spuId) {
        //找到对应spuId的商品
        Goods goods = spuService.findGoodsById(spuId);
        //得到spu信息
        Spu spu = goods.getSpu();
        //得到sku列表信息
        List<Sku> skuList = goods.getSkuList();
        //创建list,把三级分类放入list中,再把list放入模型中
        List<String> categoryList = new ArrayList<String>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());

        //创建urlMap,用来装sku的地址
        Map urlMap = new HashMap();
        //key为排过序的sku规格,value为sku的id+.html
        for (Sku sku : skuList) {
            String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
            urlMap.put(specJson,sku.getId()+".html");
        }

        //遍历sku,为每一个sku创建页面
        for (Sku sku : skuList) {
            //获取上下文并创建数据模型
            Context context = new Context();
            Map<String, Object> dataModel = new HashMap<>();
            //把spu和sku放入模型中
            dataModel.put("spu", spu);
            dataModel.put("sku", sku);
            dataModel.put("categoryList", categoryList);
            //把sku和spu的图片列表images放入模型
            dataModel.put("skuImages",sku.getImages().split(","));
            dataModel.put("spuImages",spu.getImages().split(","));
            //把spu表中的参数字段放入模型
            //把字符串形式转换成map集合
            Map<String,String> spu_paramItems = JSON.parseObject(spu.getParaItems(),Map.class);
            dataModel.put("spu_paramItems",spu_paramItems);
            //把sku表中的规格字段放入模型
            Map<String,String> sku_spec = JSON.parseObject(sku.getSpec(), Map.class);
            dataModel.put("sku_spec",sku_spec);
            //把spu表中的规格字段放入模型,但为了实现selected功能,需要修改
            //{"颜色":["红色","黑色","梵高星空典藏版"],"版本":["8GB+128GB","6GB+64GB"]}
            /*{"颜色":[{"option":"红色","checked":"true"},
                      {"option":"黑色","checked":"false"},
                      {"option":"梵高星空典藏版","checked":"false"}],
              "版本":[{"option":"8GB+128GB","checked":"true"},
                     {"option":"6GB+64GB","checked":"false"}]}*/
            Map<String,List> spu_specItems = JSON.parseObject(spu.getSpecItems(), Map.class);
            for (String key : spu_specItems.keySet()) {
                //获得原集合的value  ["红色","黑色","梵高星空典藏版"]
                List<String> spu_specListOld = spu_specItems.get(key);
                //开始改变原集合的value
                List<Map> spu_specList = new ArrayList<Map>();
                //遍历原集合的value,获得option
                for (String value : spu_specListOld) {
                    //创建map集合
                    Map<String,Object> spu_specMap = new HashMap<>();
                    //把option装入map
                    spu_specMap.put("option",value);
                    //做判断,看sku_spec的value是否和value值相同,相同checked就为true
                    if(sku_spec.get(key).equals(value)) {
                        spu_specMap.put("checked",true);
                    }else {
                        spu_specMap.put("checked",false);
                    }
                    //把原spu的spec集合中的key和value放入sku的规格集合中,这个便是当前sku的规格
                    Map<String,String> sku_spec1 = JSON.parseObject(sku.getSpec(), Map.class);
                    sku_spec1.put(key,value);
                    String specJson = JSON.toJSONString(sku_spec1, SerializerFeature.MapSortField);
                    spu_specMap.put("url",urlMap.get(specJson));
                    //把map装入list中,获得新的value
                    spu_specList.add(spu_specMap);
                }
                //替换原来的map集合spu_specItems
                spu_specItems.put(key,spu_specList);
            }
            //把spu_specItems放入模板中
            dataModel.put("spu_specItems",spu_specItems);
            context.setVariables(dataModel);
            //准备文件
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId() + ".html");
            //生成页面
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item", context, writer);
                //打印看看是否生成页面
                System.out.println("生成页面" + sku.getId() + ".html");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
